<!-- 机构管理，添加机构 -->
<template>
  <div class="pad organization">
    <div class="head">
      <span>{{ titleText }}</span>
    </div>

    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :http-request="handleUploadSchool"
    >
      <el-button
        type="primary"
        v-if="organization.type == 1"
      >批量导入学校
      </el-button>
    </el-upload>
    <el-form :model="organization" :rules="rulesForm" ref="submit" label-position="top" class="m-t-b">

      <div class="f-title">
        <div></div>
        <span>基础信息</span>
        <div></div>
      </div>

      <el-form-item label="机构类型">
        <el-radio-group v-model="organization.type">
          <el-radio :label="1">学校</el-radio>
          <el-radio :label="2">公司</el-radio>
          <el-radio :label="3">医院</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="names[organization.type - 1] + '名称'" prop="enterpriseName">
        <el-input v-model="organization.enterpriseName"/>
      </el-form-item>
      <el-form-item :label="names[organization.type - 1] + '简称'" prop="forShort">
        <el-input v-model="organization.forShort"/>
      </el-form-item>

      <el-form-item label="学校类型" v-if="organization.type === 1">
        <el-radio-group v-model="organization.schoolType">
          <el-radio :label="1">幼儿园</el-radio>
          <el-radio :label="2">小学</el-radio>
          <el-radio :label="3">初中</el-radio>
          <el-radio :label="4">高中</el-radio>
          <el-radio :label="5">大学</el-radio>
        </el-radio-group>
      </el-form-item>

<!--      选择学校时渲染-->
      <el-form-item label="学校年制" v-if="organization.type === 1">
        <el-radio-group v-model="organization.schoolYear">
          <el-radio :label="0">五四制</el-radio>
          <el-radio :label="1">六三制</el-radio>
          <el-radio :label="3">3年制</el-radio>
          <el-radio :label="4">4年制</el-radio>
          <el-radio :label="5">5年制</el-radio>
          <el-radio :label="6">6年制</el-radio>
        </el-radio-group>
      </el-form-item>
<!--选择医院时渲染-->
      <el-form-item label="医院类型" v-if="organization.type === 3">
        <el-radio-group v-model="organization.hospitalType">
          <el-radio :label="0">一甲医院</el-radio>
          <el-radio :label="1">二甲医院</el-radio>
          <el-radio :label="2">三甲医院</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="位置信息">
        <el-select v-model="organization.provinceId" clearable filterable placeholder="省" @change="changeProvince">
          <el-option v-for="item in provinceList" :key="item.id" :value="item.id" :label="item.cname"></el-option>
        </el-select>

        <el-select v-model="organization.cityId" clearable filterable placeholder="市">
          <el-option v-for="item in cityList" :key="item.id" :value="item.id" :label="item.cname"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="经纬度设置">
        <el-button type="primary" @click="openSetLocation">点击拾取经纬度</el-button>
        <span style="padding-left: 30px;">经度: {{ organization.coordinateX || '--' }}</span>
        <span style="padding-left: 10px;">纬度: {{ organization.coordinateY || '--' }}</span>
      </el-form-item>
<!--      选择公司时渲染-->
      <div v-if="organization.type === 2">
        <div class="f-title">
          <div></div>
          <span>公司基础信息</span>
          <div></div>
        </div>
        <el-form-item label="法人姓名">
          <el-input v-model="organization.legalPerson"/>
        </el-form-item>
        <el-form-item label="法人电话">
          <el-input v-model="organization.corporatePhone"/>
        </el-form-item>
        <el-form-item label="法人身份证号">
          <el-input v-model="organization.idCard"/>
        </el-form-item>
        <el-form-item label="公司地址">
          <el-input v-model="organization.address"/>
        </el-form-item>
        <el-form-item label="营业执照">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="true"
            :http-request="({ file }) => { this.customUpload(file, 'businessLicense') }"
          >
            <img v-if="organization.businessLicense" :src="organization.businessLicense" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="身份证正面">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="true"
            :http-request="({ file }) => { this.customUpload(file, 'idCardPositive') }"
          >
            <img v-if="organization.idCardPositive" :src="organization.idCardPositive" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="身份证反面">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="true"
            :http-request="({ file }) => { this.customUpload(file, 'idCardBehind') }"
          >
            <img v-if="organization.idCardBehind" :src="organization.idCardBehind" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <div class="f-title">
          <div></div>
          <span>公司负责人信息</span>
          <div></div>
        </div>
        <el-form-item label="负责人姓名">
          <el-input v-model="organization.personLiable"/>
        </el-form-item>
        <el-form-item label="负责人电话">
          <el-input v-model="organization.personLiablePhone"/>
        </el-form-item>
        <el-form-item label="负责人微信">
          <el-input v-model="organization.personLiableWechat"/>
        </el-form-item>
        <el-form-item label="负责人身份证号">
          <el-input v-model="organization.personLiableCard"/>
        </el-form-item>
        <div class="f-title">
          <div></div>
          <span>开户行信息</span>
          <div></div>
        </div>
        <el-form-item label="开户名称">
          <el-input v-model="organization.accountName"/>
        </el-form-item>
        <el-form-item label="开户行银行">
          <el-input v-model="organization.bank"/>
        </el-form-item>
        <el-form-item label="银行卡卡号">
          <el-input v-model="organization.cardNumber"/>
        </el-form-item>
        <div class="f-title">
          <div></div>
          <span>其它信息</span>
          <div></div>
        </div>
        <el-form-item label="主营业务">
          <el-input v-model="organization.mainBusiness"/>
        </el-form-item>
        <el-form-item label="所属业务">
          <el-input v-model="organization.business"/>
        </el-form-item>
        <el-form-item label="入驻时间">
          <el-date-picker
            v-model="organization.entryTime"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入驻金额">
          <el-input type="number" v-model="organization.entryAmount"/>
        </el-form-item>
        <el-form-item label="充值金额">
          <el-input type="number" v-model="organization.rechargeAmount"/>
        </el-form-item>
        <el-form-item label="公司logo">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="true"
            :http-request="({ file }) => { this.customUpload(file, 'companyLogo') }"
          >
            <img v-if="organization.companyLogo" :src="organization.companyLogo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="公司简介">
          <el-input type="textarea" rows="6" v-model="organization.companyProfile"/>
        </el-form-item>
        <el-form-item label="品牌理念">
          <el-input type="textarea" rows="6" v-model="organization.brandConcept"/>
        </el-form-item>
        <el-form-item label="门头照">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="true"
            :http-request="({ file }) => { this.customUpload(file, 'doorPhoto') }"
          >
            <img v-if="organization.doorPhoto" :src="organization.doorPhoto" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="环境照">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="true"
            :http-request="({ file }) => { this.customUpload(file, 'environment') }"
          >
            <img v-if="organization.environment" :src="organization.environment" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </div>
    </el-form>
    <el-button type="primary" @click="saveOrganizationAdmin">{{ addText }}</el-button>


    <el-dialog :visible.sync="showMap">
      <div class="map-wrap">
        <div>
          <el-input v-model="searchText" @keyup.enter.native="searchLocation">
            <el-button slot="append" @click="searchLocation">搜索</el-button>
          </el-input>
          <div class="map-box" id="mapBox" v-loading="mapLoading"></div>
        </div>
        <div id="r-result"></div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getAllArea} from '../api/hospitalAPI';
import {fileToBase64, excel2Json} from '../util';
import {uploadImage} from '../api';
import {
  addOrganization,
  getOrganizationListByType,
  alterOrganizationInfo,
} from '../api/version2';
import XLSX from 'xlsx';
import {Row} from 'element-ui';

export default {
  name: 'AddOrganization',
  data() {
    return {
      titleText: "添加机构",
      addText: "确认添加",
      names: ['学校', '公司', '医院'],
      mapLoading: false,
      provinceList: [],
      searchText: '',
      cityList: [],
      isDoing: false,
      showMap: false,
      map: null,
      organization: {
        enterpriseId: "",//且也ID
        enterpriseName: "", // 企业名称
        forShort: "", // 企业简称
        type: 1, // 企业类型(1学校，2公司，3医院)
        schoolType: "", // 学校类型(0幼儿园，1小学，2中学，3高中，4大学)
        schoolYear: "", // 学校年制
        hospitalType: "", // 医院类型(0一甲医院，1二甲医院，2三甲医院)
        provinceId: "", // 省id
        cityId: "", // 市id
        coordinateY: "", // 坐标y(纬度)
        coordinateX: "", // 坐标x(经度)
        // 添加公司使用
        legalPerson: "", // 法人姓名
        corporatePhone: "", // 法人电话
        idCard: "", // 法人身份证号
        address: "", // 地址
        businessLicense: "", // 营业执照
        idCardPositive: "", // 身份证正面
        idCardBehind: "", // 身份证反面
        personLiable: "", // 负责人姓名
        personLiablePhone: "", // 负责人电话
        personLiableWechat: "", // 负责人微信
        personLiableCard: "", // 责任人身份证号
        accountName: "", // 开户名称
        bank: "", // 开户银行
        cardNumber: "", // 银行卡号
        mainBusiness: "", // 主营业务
        business: "", // 所属业务
        entryTime: "", // 入驻时间
        entryAmount: "", // 入驻金额
        rechargeAmount: "", // 充值金额
        companyLogo: "", // 公司logo
        companyProfile: "", // 公司简介
        brandConcept: "", // 品牌理念
        doorPhoto: "", // 门头照
        environment: "" // 环境照
      },
      rulesForm: {
        enterpriseName: [
          {required: true, trigger: 'blur', message: "此项为必填项"},
        ],
        forShort: [
          {required: true, trigger: 'blur', message: "此项为必填项"},
        ]
      },
    }
  },
  methods: {
    fetchAreas(id) { // 根据id查询地区
      getAllArea(id)
        .then(res => {
          let list = res.data.data || [];
          this[id === 1 ? 'provinceList' : 'cityList'] = list
        })
        .catch(e => {
        })
    },
    changeProvince(e) { // 切换省
      this.cityList = [];
      this.organization.cityId = "";
      this.fetchAreas(e)
    },
    openSetLocation() { // 设置经纬度
      this.showMap = true;
      if (!this.map) {
        this.mapLoading = true;
        setTimeout(() => {
          this.renderMap()
        }, 1000)
      }
    },
    handleUploadSchool({file}) { // 批量导入学校
      excel2Json(file, XLSX, (worker, data) => {
        console.log(data)
      })
    },
    saveOrganizationAdmin() {
      this.$refs['submit'].validate((valid, err) => {
        if (!valid) {
          return
        }
        ;
        this.saveOrganization();
      })
    },
    saveOrganization() { // 保存/修改组织
      if (this.addText == "确认修改") {
        alterOrganizationInfo(this.organization)
          .then(res => {
            if (res.data.code == 1) {
              this.$message.success("修改成功");
              this.$router.push("/organization/list");
            } else {
              this.$message.error("修改失败");
              this.$router.push("/organization/list");
            }
          })

      } else if (this.addText == "确认添加") {
        // console.log(this.addText);
        this.isDoing = true;
        addOrganization(this.organization)
          .then(res => {
            this.$message.success('创建成功!');
            this.isDoing = false;
            // this.$router.push('/organization/list?type=' + this.organization.type)
            if (this.$route.query.idccc == 1) {
              console.log(this.$route.query.idccc);
              history.back();
            } else {
              this.$router.push('/organization/list?type=' + this.organization.type)
            }
          })
          .catch(e => {
            this.isDoing = false
          })
      }
      // this.isDoing = true;
      // addOrganization(this.organization)
      // .then(res => {
      //   this.$message.success('创建成功!');
      //   this.isDoing = false;
      //   this.$router.push('/organization/list?type=' + this.organization.type)
      // })
      // .catch(e => {
      //   this.isDoing = false
      // })
    },
    customUpload(file, type) { // 上传图标
      const _this = this;
      fileToBase64(file, base64Str => {
        uploadImage(base64Str)
          .then(res => {
            let path = res.data.data.path;
            path = path.replace('http:', 'https:');
            _this.organization[type] = path
          })
          .catch(e => {
          })
      })
    },
    renderMap() {
      var map = new BMap.Map("mapBox");
      var point = new BMap.Point(116.404, 39.915);
      map.centerAndZoom(point, 20);
      this.map = map;
      this.addClickEvent()
      this.getNavigatorLocation(map);
    },
    getNavigatorLocation(map) { // 获取当前位置
      var geolocation = new BMap.Geolocation();
      const that = this;
      geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          var mk = new BMap.Marker(r.point);
          map.addOverlay(mk);
          map.panTo(r.point);
          that.mapLoading = false;
          console.log(r.point.lng, r.point.lat)
        } else {
          that.$message.error('获取位置信息错误, 状态码: ' + this.getStatus())
        }
      }, {enableHighAccuracy: true})
    },
    addClickEvent() {
      const _this = this;
      this.map.addEventListener("click", function (e) {
        _this.organization.coordinateX = e.point.lng;
        _this.organization.coordinateY = e.point.lat
      });
    },
    searchLocation() { // 搜索位置信息
      if (!this.searchText.trim()) {
        return this.$message.error('搜索内容不能为空!')
      }
      ;
      let map = this.map;
      // map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
      let local = new BMap.LocalSearch(map, {
        renderOptions: {map: map, panel: "r-result"}
      });
      local.search(this.searchText);
    }
  },
  created() {
    let query = this.$route.query;
    console.log(query);
    if (query.type) {
      this.organization.type = Number(query.type)
    }
    ;
    this.fetchAreas(1);
    // this.getNavigatorLocation()
    if (query.id) {
      this.addText = "确认修改";
      this.titleText = "修改机构信息";
      getOrganizationListByType({
        index: 1,
        count: 10,
        queryParam: {
          // enterpriseId: query.id,
          enterpriseId: query.id,
        }
      }).then(res => {
        let list = res.data.data.list[0] || [];
        console.log(list);
        this.organization.enterpriseName = list.enterpriseName;
        this.organization.forShort = list.forShort;
        this.organization.schoolType = list.schoolType;
        this.organization.schoolYear = list.schoolYear;
        this.organization.hospitalType = list.hospitalType;
        this.organization.provinceId = list.provinceId;
        this.organization.cityId = list.cityId;
        this.organization.enterpriseId = list.enterpriseId;
      });
    }
  },
}
</script>
<style lang="scss">
.f-title {
  display: flex;
  align-items: center;

  div {
    flex: 1;
    height: 1px;
    background-color: #4AC493;
  }

  span {
    padding: 0 10px;
    font-size: 18px;
    font-weight: bold;
    color: #4AC493;
  }
}

.map-box {
  height: 60vh;
}

.map-wrap {
  display: flex;

  & > div:nth-of-type(1) {
    flex: 1;
  }

  #r-result {
    width: 300px;
    flex-shrink: 0;
  }
}
</style>
